﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QuanLyDeTaiKHCN.Obj_class;
using SecurityLib;
namespace QuanLyDeTaiKHCN.UserControls
{
    public partial class DanhMucLinhVuc : System.Web.UI.UserControl
    {
        _dbDataContext _db = new _dbDataContext();
        Sec_AES _se = new Sec_AES();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        protected void BindGrid()
        {
            int loai = int.Parse(_se.Decrypt(Request.QueryString["f"].Replace(" ", "+"), "gold", 128));
            var list = from p in _db.tblDanhMucs.Where(r=>r.Loai==loai) select new { ID=p.ID,TenLinhVuc=p.TenDanhMuc.Trim()};
            grid.DataSource = list.ToList();
            grid.DataBind();
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            if (txtTenLinhVuc.Text == "")
            {
                lblstatus.Text = "Nhập tên lĩnh vực trước khi lưu";
            }
            else
            {
                int loai = int.Parse(_se.Decrypt(Request.QueryString["f"].Replace(" ", "+"), "gold", 128));
                if (CatalogAccess.InsertDanhMuc(txtTenLinhVuc.Text,loai))
                {
                    BindGrid();
                    txtTenLinhVuc.Text = "";
                    txtTenLinhVuc.Focus();
                }
                else
                {
                    lblstatus.Text = "Có lỗi khi lưu."; 
                }
            }
        }
        protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = int.Parse(grid.DataKeys[e.RowIndex].Value.ToString());
            if (CatalogAccess.DeleteDanhMuc(id))
            {
                BindGrid();
            }
        }

        protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grid.EditIndex = e.NewEditIndex;
            BindGrid();
        }

        protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grid.EditIndex = -1;
            BindGrid();
        }

        protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int id = int.Parse(grid.DataKeys[e.RowIndex].Value.ToString());
            string ten = ((TextBox)grid.Rows[e.RowIndex].FindControl("txtTenLinhVuc")).Text;
            if (CatalogAccess.UpdateDanhMuc(id, ten))
            {
                grid.EditIndex = -1;
                BindGrid();
            }
            else
            {
                grid.EditIndex = -1;
            }
        }
    }
}